{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qjQ5KQIkaK2J"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "\n",
        "## Install dependencies\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install wget\n",
        "!pip install text-unidecode\n",
        "\n",
        "### Install NeMo\n",
        "BRANCH = 'main'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "J6d04-VRjC-O"
      },
      "outputs": [],
      "source": [
        "### Install Hugging Face Hub\n",
        "!python -m pip install huggingface_hub\n",
        "!python -m pip install evaluate\n",
        "!python -m pip install ipywidgets"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aS-Y5O_oGBTc"
      },
      "source": [
        "# NeMo models on Hugging Face Hub\n",
        "\n",
        "This guide will briefly show how to upload NeMo models to Hugging Face programmatically.\n",
        "\n",
        "This enables community members to share their NeMo models (any model!) with all users of NeMo!\n",
        "\n",
        "**Note**: While in this tutorial we showcase an ASR model, there is no particular restriction to any domain - all NeMo models (.nemo files) of every domain can be uploaded and shared in the same way."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Us3UlvwCiEZi"
      },
      "source": [
        "# Login to Hugging Face\n",
        "\n",
        "Use the notebook login, and access your user access token (or create one to upload models to Hugging Face).\n",
        "\n",
        "For more information, visit the User Access Token section - https://huggingface.co/docs/hub/security-tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4RTYbCLziEnb"
      },
      "outputs": [],
      "source": [
        "from huggingface_hub import notebook_login\n",
        "\n",
        "notebook_login()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dgZbTPcFiaml"
      },
      "outputs": [],
      "source": [
        "!git config --global credential.helper store"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s-FiNn1eiFAl"
      },
      "source": [
        "# Prepare a model to upload to HF\n",
        "\n",
        "In this example, we will download a NeMo ASR model from NGC and then upload it to Hugging Face for simplicity and to showcase the method.\n",
        "\n",
        "**You can swap out this ASR model for any model that you restore via `restore_from()` and follow the same steps to upload your own models !**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5KnVl-M0ax14"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "import torch.nn as nn\n",
        "\n",
        "from omegaconf import DictConfig, OmegaConf, open_dict"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZEDpkIinbwmm"
      },
      "outputs": [],
      "source": [
        "import nemo.collections.asr as nemo_asr  # use any domain's models !\n",
        "import nemo.collections.tts as nemo_tts  # use any domain's models !"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mLuQo1vnHVcP"
      },
      "source": [
        "# Model Name\n",
        "\n",
        "NeMo adheres to strict requirements when naming a model for upload to NGC / Hugging Face Hub.\n",
        "\n",
        "It is **mandatory** to share the model name across the model card, the NeMo file itself. Otherwise NeMo model from Hugging Face will fail to restore correctly."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MRO2f9fhHywJ"
      },
      "source": [
        "## Naming Convention\n",
        "\n",
        "NeMo model names can vary based on domain and purpose. While we attempt to conform to standard guidelines when naming our models, we do not expect the same level of strictness for community contributions.\n",
        "\n",
        "Here are some common guidelines we encourage (but do not enforce) users to follow :\n",
        "\n",
        "- `Task name`: Usually a short 2-3 character representation of the task that the model performs.\n",
        "  - `stt` = Speech To Text (ASR)\n",
        "  - `tts` = Text to Speech (TTS)\n",
        "  - `ssl` = (Speech) Self Supervised Learning (SSL)\n",
        "  - `nmt` = Neural Machine Translation (NMT) and many more.\n",
        "\n",
        "- `Language ID`: Usually a 2/3 digit universal language id. For multilingual models, each domain has its own rules, but some common ones are `{lang_1}{lang_2}{...}` or call them `multilingual.`\n",
        "\n",
        "- `Model Identifier`: Since models vary so drastically across domains, there is a lot of flexibility here. We try to adhere to naming conventions in literature as much as possible. For example, you can attach `model architecture` (Conformer/Citrinet), `training loss` (CTC/Transducer), and `model size` (small, large, discrete integer sizes, etc.).\n",
        "\n",
        "- `Optional: Additional Modifiers`: These are additional identifiers such as gender of speaker (TTS), dataset name (ls for Librispeech), etc. It can be set on a case-by-case basis.\n",
        "\n",
        "All these name segments are jointed by `_`.\n",
        "\n",
        "-----\n",
        "\n",
        "As an example of the following model we will try today :\n",
        "\n",
        "`{task name}_{language id}_{model identifier}_[OPTIONAL modifiers]` = `stt_en_conformer_ctc_small`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BjLstKWnPzWV"
      },
      "source": [
        "**Set the MODEL_NAME carefully** !"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UzHjXDbckU0M"
      },
      "outputs": [],
      "source": [
        "MODEL_NAME = \"stt_en_conformer_ctc_small\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qibj1RwvKjSQ"
      },
      "source": [
        "-----\n",
        "**Restore a NeMo Model**\n",
        "\n",
        "Here, we restore a model from NGC directly, but you can restore a model from your training runs using `restore_from()` or use a local .nemo file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MsC3pE65d_z2"
      },
      "outputs": [],
      "source": [
        "model = nemo_asr.models.ASRModel.from_pretrained(MODEL_NAME)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y1AkXPFVKfC2"
      },
      "source": [
        "# Create a Hugging Face Model\n",
        "\n",
        "Now that we have a NeMo model and have logged into Hugging Face with our user API key, we can begin by creating a new repository and uploading our model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iv17qFG7KzlL"
      },
      "source": [
        "-----\n",
        "\n",
        "After the model has been restored, create an HfApi object to interact with the model repository."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aJUXCOTjKy-2"
      },
      "outputs": [],
      "source": [
        "from huggingface_hub import HfApi\n",
        "api = HfApi()\n",
        "username = api.whoami()['name']"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DKRlMeaEkeAH"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "  api.create_repo(repo_id=MODEL_NAME)\n",
        "  print(\"Successfully created repository !\")\n",
        "except Exception as e:\n",
        "  print(\"Repository is possibly already created. Refer to error here - \\n\\n\", e)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ij6npcneH5tM"
      },
      "source": [
        "## Uploading a model to the hub\n",
        "\n",
        "There are two ways to upload a NeMo model to the Hugging Face hub -\n",
        "\n",
        "1) `push_to_hf_hub()`: This is the recommended and automated way to upload NeMo models to the HuggingFace Hub. NeMo will handle all parts of checkpoint and artifact management for you.\n",
        "\n",
        "2) Hugging Face Hub API: We provide steps to use the lower level Hugging Face Hub API to manually upload a NeMo checkpoint to the hub."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cANDXRY9ImuW"
      },
      "source": [
        "### Automatic Upload\n",
        "\n",
        "First, let's take a look at the automated way to upload a checkpoint to the hub *after* creating an empty model.\n",
        "\n",
        "One important argument is `pack_nemo_file` which decides whether to upload a single `.nemo` file to the hub, or the unpacked NeMo file (with all the individual components of the NeMo file extracted into the directory)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eCn7y9BmJGEe"
      },
      "outputs": [],
      "source": [
        "repo_id = f'{username}/{MODEL_NAME}'\n",
        "\n",
        "model.push_to_hf_hub(repo_id=repo_id, pack_nemo_file=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "62W_zIBrM563"
      },
      "source": [
        "----\n",
        "\n",
        "Before showing the manual approach, lets remove the uploaded repository first"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Mqu0Aqg2M8ly"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "  api.delete_repo(repo_id=MODEL_NAME, missing_ok=True)\n",
        "  api.create_repo(repo_id=MODEL_NAME)\n",
        "  print(\"Successfully created repository !\")\n",
        "except Exception as e:\n",
        "  print(\"Repository is possibly already created. Refer to error here - \\n\\n\", e)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UJYwaRA9I1Oc"
      },
      "source": [
        "### Manual Upload\n",
        "\n",
        "Next, let's take a look at how to use the Hugging Face Hub API to upload a NeMo checkpoint to the hub.\n",
        "\n",
        "Note: Both ways will get similar results, so we recommend the automated way to make it easier."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aTa4RqDYLGMI"
      },
      "source": [
        "Note two essential names -\n",
        "\n",
        "- `hf_model_name`: A string name that is the composite of your `username` and `MODEL_NAME` as set above. This name is used for multiple purposes, so keep track of it.\n",
        "\n",
        "- `model_filename`: The actual filename of the NeMo model that will be uploaded to Hugging Face. Note that this filename is explicitly set to `{MODEL_NAME}.nemo`. If this model filename is altered, then the model cannot correctly be restored by NeMo when downloaded from Hugging Face Hub, so please be careful."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xhTTMNpBskMS"
      },
      "outputs": [],
      "source": [
        "from huggingface_hub import upload_file\n",
        "import os\n",
        "\n",
        "model_filename = f'{MODEL_NAME}.nemo'\n",
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "commit_message = \"Upload model\"\n",
        "path_in_repo = model_filename\n",
        "\n",
        "model.save_to(model_filename)\n",
        "\n",
        "upload_file(\n",
        "    path_or_fileobj=model_filename,\n",
        "    path_in_repo=path_in_repo,\n",
        "    repo_id=hf_model_name,\n",
        "    commit_message=commit_message,\n",
        "    repo_type='model',\n",
        ")\n",
        "\n",
        "os.remove(model_filename)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BhvNp8MYvxLi"
      },
      "outputs": [],
      "source": [
        "print(\"Finished uploading model to :\", hf_model_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Qrs-MlW9vVbH"
      },
      "source": [
        "## Test if the model works\n",
        "\n",
        "Now that we uploaded the model, let's try to use it in NeMo !\n",
        "\n",
        "The only change required between normally calling `from_pretrained(model_name)` is to call **`from_pretrained({username}/{filename})`**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NyuyyRv5snkr"
      },
      "outputs": [],
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "hf_model = nemo_asr.models.ASRModel.from_pretrained(hf_model_name)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Yhi922WVv4G_"
      },
      "outputs": [],
      "source": [
        "print(\"Successfully used HF model -\", hf_model_name)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9gG1ElJywEJT"
      },
      "source": [
        "# Model Card\n",
        "\n",
        "Now that we have uploaded the model, we are nearly 50% done!\n",
        "\n",
        "The next step is to update the model card to have some helpful information regarding the uploaded model and its scores compared to other models.\n",
        "\n",
        "You can do this in two ways, manually (by clicking the link below) or programmatically fill in part of the model card by following the instructions below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aZJRKoxhwBLr"
      },
      "outputs": [],
      "source": [
        "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n",
        "print(f\"Visit {hf_url} to manually edit your model card\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZlA4hNq6w4rH"
      },
      "source": [
        "-----\n",
        "\n",
        "Here, we are going to setup some variables for our model card.\n",
        "\n",
        "First up are the tags:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QxKtPynWyUWX"
      },
      "outputs": [],
      "source": [
        "TAGS = [\n",
        "    \"automatic-speech-recognition\",  # Task id, refer to https://github.com/huggingface/datasets/blob/master/src/datasets/utils/resources/tasks.json for allowed values.\n",
        "    \"speech\",  # add as many other tags as required\n",
        "    \"audio\",\n",
        "    \"CTC\",\n",
        "    \"Conformer\",\n",
        "    \"Transformer\",\n",
        "    \"NeMo\",  # required for library identification\n",
        "    \"pytorch\",  # required, for toolkit identification\n",
        "    # \"hf-asr-leaderboard\",  # Should only be used if model is evaluated on benchmark scores for ASR.\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fh7rYWEMM0Vz"
      },
      "source": [
        "-----\n",
        "\n",
        "Next, we list down all the datasets that were used to train the model.\n",
        "\n",
        "By convention, try to search if the dataset already exists on Hugging Face Datasets - it is usually listed at the top and in lower case.\n",
        "\n",
        "If you train on datasets that don't yet exist in Hugging Face Datasets, you can still add them but try to differentiate them by using capitalized names."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qy-5aDAgzuGD"
      },
      "outputs": [],
      "source": [
        "# Replace all spaces with `-`\n",
        "DATASETS = [\n",
        "    \"librispeech_asr\",\n",
        "    \"mozilla-foundation/common_voice_7_0\",\n",
        "    \"vctk\",\n",
        "    \"fisher_corpus\",\n",
        "    \"Switchboard-1\",\n",
        "    \"WSJ-0\",\n",
        "    \"WSJ-1\",\n",
        "    \"National-Singapore-Corpus-Part-1\",\n",
        "    \"National-Singapore-Corpus-Part-6\",\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_0w1X_z4NN5-"
      },
      "source": [
        "-----\n",
        "\n",
        "Now we create an automated template based on a config for the top portion of the readme file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "O88WFyPJwjJD"
      },
      "outputs": [],
      "source": [
        "from dataclasses import dataclass, field\n",
        "from typing import List, Optional, Dict, Any\n",
        "\n",
        "@dataclass\n",
        "class NeMoHuggingFaceModelConfig:\n",
        "  language: List[str]\n",
        "  license: str\n",
        "\n",
        "  library_name: str = \"nemo\"\n",
        "  datasets: List[str] = field(default_factory=lambda: DATASETS)\n",
        "  thumbnail: Optional[str] = None\n",
        "  tags: List[str] = field(default_factory=lambda: TAGS)\n",
        "  model_index: Any = field(default_factory=lambda: [dict(name=MODEL_NAME, results=[])])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BpInrBdNxxZ3"
      },
      "outputs": [],
      "source": [
        "config = NeMoHuggingFaceModelConfig(language=['en'], license=\"cc-by-4.0\")  # choose appropriate license here\n",
        "config = OmegaConf.structured(config)\n",
        "\n",
        "with open_dict(config):\n",
        "  # Update `model_index` to `model-index`\n",
        "  model_index = config.pop('model_index')\n",
        "  config['model-index'] = model_index\n",
        "\n",
        "  # Replace all spaces with `-` in datasets\n",
        "  normalized_datasets = [ds_name.replace(\" \", \"-\") for ds_name in config['datasets']]\n",
        "  config['datasets'] = OmegaConf.create(normalized_datasets)\n",
        "\n",
        "print(OmegaConf.to_yaml(config))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0TECX8QrC6FY"
      },
      "source": [
        "## Markdown Template\n",
        "\n",
        "Now that we have an auto-generated header for our readme, next, we write down some template markdown for the actual contents of the markdown.\n",
        "\n",
        "You can edit the code here directly if you want, or if you prefer the GUI to see the actual changes in real-time, you can finish uploading this model card and then edit the readme file on the Hugging Face webpage itself."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SSmm7_OiC9Ex"
      },
      "outputs": [],
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "\n",
        "TEMPLATE = f\"\"\"\n",
        "## Model Overview\n",
        "\n",
        "<DESCRIBE IN ONE LINE THE MODEL AND ITS USE>\n",
        "\n",
        "## NVIDIA NeMo: Training\n",
        "\n",
        "To train, fine-tune or play with the model you will need to install [NVIDIA NeMo](https://github.com/NVIDIA/NeMo). We recommend you install it after you've installed latest Pytorch version.\n",
        "```\n",
        "pip install nemo_toolkit['all']\n",
        "```\n",
        "\n",
        "## How to Use this Model\n",
        "\n",
        "The model is available for use in the NeMo toolkit [3], and can be used as a pre-trained checkpoint for inference or for fine-tuning on another dataset.\n",
        "\n",
        "### Automatically instantiate the model\n",
        "\n",
        "```python\n",
        "import nemo.collections.asr as nemo_asr\n",
        "asr_model = nemo_asr.models.ASRModel.from_pretrained(\"{hf_model_name}\")\n",
        "```\n",
        "\n",
        "### Transcribing using Python\n",
        "First, let's get a sample\n",
        "```\n",
        "wget https://dldata-public.s3.us-east-2.amazonaws.com/2086-149220-0033.wav\n",
        "```\n",
        "Then simply do:\n",
        "```\n",
        "asr_model.transcribe(['2086-149220-0033.wav'])\n",
        "```\n",
        "\n",
        "### Transcribing many audio files\n",
        "\n",
        "```shell\n",
        "python [NEMO_GIT_FOLDER]/examples/asr/transcribe_speech.py \\\n",
        " pretrained_name=\"{hf_model_name}\" \\\n",
        " audio_dir=\"<DIRECTORY CONTAINING AUDIO FILES>\"\n",
        "```\n",
        "\n",
        "### Input\n",
        "\n",
        "This model accepts 16000 KHz Mono-channel Audio (wav files) as input.\n",
        "\n",
        "### Output\n",
        "\n",
        "This model provides transcribed speech as a string for a given audio sample.\n",
        "\n",
        "## Model Architecture\n",
        "\n",
        "<ADD SOME INFORMATION ABOUT THE ARCHITECTURE>\n",
        "\n",
        "## Training\n",
        "\n",
        "<ADD INFORMATION ABOUT HOW THE MODEL WAS TRAINED - HOW MANY EPOCHS, AMOUNT OF COMPUTE ETC>\n",
        "\n",
        "### Datasets\n",
        "\n",
        "<LIST THE NAME AND SPLITS OF DATASETS USED TO TRAIN THIS MODEL (ALONG WITH LANGUAGE AND ANY ADDITIONAL INFORMATION)>\n",
        "\n",
        "## Performance\n",
        "\n",
        "<LIST THE SCORES OF THE MODEL -\n",
        "      OR\n",
        "USE THE Hugging Face Evaluate LiBRARY TO UPLOAD METRICS>\n",
        "\n",
        "## Limitations\n",
        "\n",
        "<DECLARE ANY POTENTIAL LIMITATIONS OF THE MODEL>\n",
        "\n",
        "Eg:\n",
        "Since this model was trained on publicly available speech datasets, the performance of this model might degrade for speech which includes technical terms, or vernacular that the model has not been trained on. The model might also perform worse for accented speech.\n",
        "\n",
        "\n",
        "## References\n",
        "\n",
        "<ADD ANY REFERENCES HERE AS NEEDED>\n",
        "\n",
        "[1] [NVIDIA NeMo Toolkit](https://github.com/NVIDIA/NeMo)\n",
        "\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KPa53S_5NzNp"
      },
      "source": [
        "-----\n",
        "\n",
        "Below, we will upload this model card in a temporary file called **`\"readme_template.md\"`**. This is done to prevent overwriting of the \"final\" model card that the user may have manually edited.\n",
        "\n",
        "Once this step is finished, **please copy the contents of this file, create a README.md file and paste the contents into it**."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0vk5KK4gzpSU"
      },
      "outputs": [],
      "source": [
        "filename = 'readme_template.md'\n",
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "commit_message = \"Upload config\"\n",
        "path_in_repo = 'README.md'\n",
        "\n",
        "with open(filename, 'w') as f:\n",
        "    f.write(\"---\\n\")\n",
        "    f.write(OmegaConf.to_yaml(config))\n",
        "    f.write(\"\\n---\\n\\n\")\n",
        "    f.write(TEMPLATE)\n",
        "\n",
        "upload_file(\n",
        "    path_or_fileobj=filename,\n",
        "    path_in_repo=path_in_repo,\n",
        "    repo_id=hf_model_name,\n",
        "    commit_message=commit_message,\n",
        "    repo_type='model',\n",
        ")\n",
        "\n",
        "os.remove(filename)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dfXoihCQmWDa"
      },
      "source": [
        "-----\n",
        "\n",
        "Please visit the URL below to copy the contents of the `readme_template.md` file into your `README.md` file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "but-5LuLTHFd"
      },
      "outputs": [],
      "source": [
        "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n",
        "print(f\"Visit {hf_url} to edit your model card from the generated template file `{filename}`\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5vPEnlE62dGU"
      },
      "source": [
        "## Evaluation Results\n",
        "\n",
        "Now that we have both the model checkpoint and the readme uploaded to the Hub, we can optionally add some evaluation results to the card as well!\n",
        "\n",
        "While this next section is optional, it is highly encouraged to do!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rkXMtapA0YzH"
      },
      "outputs": [],
      "source": [
        "import evaluate\n",
        "# evaluate.list_evaluation_modules(module_type='metric', with_details=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "50rzG9Qb3yLR"
      },
      "outputs": [],
      "source": [
        "# Uncomment in order to see what values you can supply to the `evaluate` library to push to the Hub.\n",
        "# help(evaluate.push_to_hub)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5A4g3SGf4d0V"
      },
      "outputs": [],
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "metric_value = 8.1  # value obtained from https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_conformer_ctc_small\n",
        "\n",
        "evaluate.push_to_hub(\n",
        "    model_id=hf_model_name,\n",
        "    task_type=\"automatic-speech-recognition\",\n",
        "    dataset_type=\"librispeech_asr\",\n",
        "    dataset_name=\"Librispeech (clean)\",\n",
        "    metric_type=\"wer\",\n",
        "    metric_name=\"WER\",\n",
        "    dataset_split=\"test\",  # corresponds to test-clean set\n",
        "    dataset_config=\"other\",  # corresponds to test-clean set\n",
        "    dataset_args=dict(language=\"en\"),  # metadata for dataset\n",
        "    # the actual score obtained by the model\n",
        "    metric_value=metric_value,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f3YYa7liO_m3"
      },
      "source": [
        "-----\n",
        "\n",
        "Done! Now we have a model checkpoint, a model card as well as evaluation results all set up for the NeMo model on Hugging Face!\n",
        "\n",
        "To add more metrics, you can copy-paste the above cell and repeat the procedure for as many metrics as needed!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EtIMGjGwN3fa"
      },
      "source": [
        "# Bonus: Uploading a Model and its Model Card automatically\n",
        "\n",
        "`push_to_hf_hub()` also supports uploading a model card to Hugging Face Hub in the same step, so here we show an example of this feature."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "b1PSkKZVHREc"
      },
      "outputs": [],
      "source": [
        "# Use a different repo name (v2)\n",
        "try:\n",
        "  api.create_repo(repo_id=MODEL_NAME + \"_v2\")\n",
        "  print(\"Successfully created repository !\")\n",
        "except Exception as e:\n",
        "  print(\"Repository is possibly already created. Refer to error here - \\n\\n\", e)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "L4yX-ULnO9EO"
      },
      "outputs": [],
      "source": [
        "# Add some rows to template with placeholders wrapped by {}\n",
        "TEMPLATE_2 = TEMPLATE + \"\"\"\n",
        "## Original Model Name: {model_name}\n",
        "## Repo ID: {repo_id}\n",
        "\"\"\"\n",
        "kwargs = {\"model_name\": \"ABC\", \"repo_id\": \"nvidia/ABC_XYZ\"}\n",
        "model_card_v2 = model.generate_model_card(template=TEMPLATE_2, template_kwargs=kwargs, type=\"hf\")  # This is a HF ModelCard object"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AgZ5zxVwPNWr"
      },
      "outputs": [],
      "source": [
        "model.push_to_hf_hub(repo_id=hf_model_name + \"_v2\", pack_nemo_file=False, model_card=model_card_v2)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WDgwrr2aQyUS"
      },
      "outputs": [],
      "source": [
        "hf_model2 = nemo_asr.models.ASRModel.from_pretrained(hf_model_name + \"_v2\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "unQ-6_2-RUFB"
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
